package com.sy.nio.c1;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static com.sy.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author yumax
 * @Date 2024 01 06 13 41
 **/
@Slf4j
public class AioFileChannel {

    public static void main(String[] args) {

        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("nio_demo//data.txt"),
                StandardOpenOption.READ)) {

            final ByteBuffer buffer = ByteBuffer.allocate(20);
            //参数1 ByteBuffer
            //参数2 读取的起始位置
            //参数3 附件
            //参数4 回调对象
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer integer, ByteBuffer byteBuffer) {
                    log.debug(" len ...{}", integer);
                    byteBuffer.flip();
                    debugAll(byteBuffer);
                }

                @Override
                public void failed(Throwable throwable, ByteBuffer byteBuffer) {

                }
            });

            System.in.read();

        } catch (IOException e) {
            e.printStackTrace();
        }
        ;
    }
}
